package cn.tiltglass.service.impl;

import cn.tiltglass.client.RedisClient;
import cn.tiltglass.domain.Sso;
import cn.tiltglass.domain.VipBase;
import cn.tiltglass.mapper.SsoMapper;
import cn.tiltglass.mapper.VipBaseMapper;
import cn.tiltglass.service.ISsoService;
import cn.tiltglass.util.AjaxResult;
import cn.tiltglass.util.StrUtils;
import cn.tiltglass.util.encrypt.MD5;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.baomidou.mybatisplus.service.impl.ServiceImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import java.util.List;
import java.util.Map;
import java.util.UUID;

/**
 * <p>
 * 会员登录账号 服务实现类
 * </p>
 *
 * @author tiltglass
 * @since 2020-02-29
 */
@Service
public class SsoServiceImpl extends ServiceImpl<SsoMapper, Sso> implements ISsoService {
    @Autowired
    private SsoMapper ssoMapper;

    @Autowired
    private VipBaseMapper vipBaseMapper;

    @Autowired
    private RedisClient redisClient;

    @Override
    public AjaxResult login(Sso sso) {
        //校验用户是否存在,状态ok,是否已经过期等待
        if (!StringUtils.hasLength(sso.getPhone()) || !StringUtils.hasLength(sso.getPassword()))
            return AjaxResult.me().setSuccess(false).setMessage("请输入用户名或密码!");

        List<Sso> ssoList = ssoMapper.selectList(new EntityWrapper<Sso>()
                .eq("phone", sso.getPhone()));
        if (ssoList==null || ssoList.size()<1)
            return  AjaxResult.me().setSuccess(false).setMessage("用户不存在,请注册后再来登录!");

        //从数据库查询sso
        Sso ssoExsit = ssoList.get(0);

        //进行密码比对-输入密码+数据库盐值=md5再和数据库密码比对
        System.out.println(sso.getPassword());
        System.out.println(ssoExsit.getSalt());
        String md5Pwd = MD5.getMD5(sso.getPassword() + ssoExsit.getSalt());
        System.out.println(md5Pwd);
        if (!ssoExsit.getPassword().equals(md5Pwd)){
            return  AjaxResult.me().setSuccess(false).setMessage("请输入正确的用户名或密码!");
        }

        //用户存到redis并且返回token-60*30
        String accessToken = UUID.randomUUID().toString();
        redisClient.addForTime(accessToken, JSONObject.toJSONString(ssoExsit),30*60);
        return AjaxResult.me().setResultObj(accessToken);
    }

    @Override
    public Sso querySso(String accessToken) {
        //登录时已经存放了redis,直接从redis获取就ok
        String sso = redisClient.get(accessToken);
        return JSONObject.parseObject(sso,Sso.class);
    }

    public static void main(String[] args) {

        String md5 = MD5.getMD5("1" + "szYCdrDehOmArvMU49htAIqgKWIVSTkT");
        System.out.println(md5);
    }

    @Override
    public AjaxResult register(Map<String, String> params) {
        String mobile = params.get("mobile");
        String password = params.get("password");
        String smsCode = params.get("smsCode");
        //1 校验
        AjaxResult ajaxResult = validateParam(mobile,password,smsCode);
        if (!ajaxResult.isSuccess())
            return ajaxResult;
        // 2 保存sso信息
        Sso sso = new Sso();
        sso.setPhone(mobile);
        //获取随机验证-32位随机字符串
        String salt = StrUtils.getComplexRandomString(32);
        sso.setSalt(salt);
        //使用随机验证给密码md5加密,并设置
        //输入密码+以后做校验的时候先从数据库查询盐=md5,再和数据库查询出来进行比较
        String md5Password = MD5.getMD5(password + salt);
        sso.setPassword(md5Password);
        sso.setNickName(mobile);
        sso.setSecLevel(0);
        sso.setBitState(7L); // 二进制位来表示 2个小时(扩展)
        sso.setCreateTime(System.currentTimeMillis());
        ssoMapper.insert(sso);
        // 3 保存关联对象信息vipbase
        VipBase vipBase = new VipBase();
        vipBase.setCreateTime(System.currentTimeMillis());
        vipBase.setSsoId(sso.getId());
        vipBase.setRegChannel(1);
        vipBase.setRegTime(System.currentTimeMillis());
        vipBaseMapper.insert(vipBase);
        return AjaxResult.me();
    }



    private AjaxResult validateParam(String mobile,String password,String smsCode){
        // 手机号密码null校验
        if (!StringUtils.hasLength(mobile) || !StringUtils.hasLength(password))
            return AjaxResult.me().setSuccess(false).setMessage("请输入用户名或密码!");
        // 手机号时候已经注册
        List<Sso> ssoList = ssoMapper.selectList(new EntityWrapper<Sso>().eq("phone", mobile));
        if (ssoList!=null&&ssoList.size()>0)
            return AjaxResult.me().setSuccess(false).setMessage("您已经注册过了!可以直接使用!");
        // 短信验证码校验 通过key从redis获取
        String smsCodeStr = redisClient.get("SMS_CODE:" + mobile); // code:time
        String smsCodeOfRedis = smsCodeStr.split(":")[0];
        if (!smsCodeOfRedis.equals(smsCode))
            return AjaxResult.me().setSuccess(false).setMessage("请输入正确短信验证码");

        return AjaxResult.me();
    }
}
